

$(document).ready(function () {
    init();
    animate();
})

let scene, camera, renderer, controls;
var hemiLight, dirLight, uLight;

var labelRenderer;
/* 场景 */
function initScene() {

    scene = new THREE.Scene();
    scene.background = new THREE.Color().setHSL(0.6, 0, 1);
    scene.fog = new THREE.Fog(scene.background, 1, 5000);

}

/* 相机 */
function initCamera() {


    camera = new THREE.PerspectiveCamera(45, $('#model-con').width() / $('#model-con').height(), 0.1, 10000);
    camera.position.set(-10, 10, 14);
    camera.lookAt(new THREE.Vector3(0, 0, 0));

}

/* 渲染器 */
function initRender() {


    renderer = new THREE.WebGLRenderer({ antialias: true, logarithmicDepthBuffer: true });

    renderer.setSize($('#model-con').width(), $('#model-con').height());
    renderer.gammaOutput = true;
    // 开启阴影支持
    renderer.shadowMap.enabled = true;
    // 阴影类型
    renderer.shadowMap.type = THREE.PCFSoftShadowMap;

    $('#model-con').append(renderer.domElement);



    labelRenderer = new THREE.CSS2DRenderer(); //新建CSS2DRenderer 
    labelRenderer.setSize($('#model-con').width(), $('#model-con').height());

    $('#model-con').append(labelRenderer.domElement);




}

/* 灯光 */
function initLight() {
    // 环境光

    hemiLight = new THREE.HemisphereLight(0xffffff, 0xffffff, 0.8);

    hemiLight.position.set(0, 20, 0);
    scene.add(hemiLight);


    //平行光

    dirLight = new THREE.DirectionalLight(0X7F6D4D, .7);
    dirLight.color.setHSL(0.1, 1, 0.95);
    dirLight.position.set(-1, 1.75, 1);
    dirLight.position.multiplyScalar(30);
    scene.add(dirLight);

}

/* 控制器 */
function initControls() {

    /* 控件 */
    controls = new THREE.OrbitControls(camera, renderer.domElement);

    /* 属性参数 */
    controls.enableDamping = true;// 启用动态阻尼时需要一个动画循环
    controls.dampingFactor = 0.8;

    controls.screenSpacePanning = false;// 若为 true 则可以平移

    controls.maxDistance = 5000;
    controls.minDistance = 10;


    controls.autoRotate = false;


    // controls.target = scene.position;
    // controls.target.set(-30, 0, 50);

    // 上下旋转范围
    controls.maxPolarAngle = Math.PI / 2.2;
    // controls.minPolarAngle = Math.PI / 5;

    // 左右旋转范围
    // controls.minAzimuthAngle = -Math.PI * (13 / 180);
    // controls.maxAzimuthAngle = Math.PI * (13 / 180);



}
/* 场景中的内容 */
var water, labelArr = [], loadIndex = 1;;
function initContent() {

    let gLTFLoader = new THREE.GLTFLoader();

    gLTFLoader.load('../model/无标题.glb', function (gltf) {

        gltf.scene.traverse(function (node) {

            if (node.name.indexOf("T-") > -1 && node.name.split('-')[2] == "0") {

                labelArr.push({
                    x: node.position.x,
                    y: node.position.y + 2,
                    z: node.position.z,
                    name: node.name.split('-')[0] + '-' + node.name.split('-')[1]
                })

            }



            if (node.isLight) {
                // 光源阴影处理
                node.shadow.mapSize.width = 2048;
                node.shadow.mapSize.height = 2048;

                var d = 50;

                node.shadow.camera.left = -d;
                node.shadow.camera.right = d;
                node.shadow.camera.top = d;
                node.shadow.camera.bottom = -d;

                node.shadow.camera.far = 3500;
                node.shadow.bias = -0.0001;
            }


            if (node.isMesh || node.isLight) node.castShadow = true;
            if (node.isMesh || node.isLight) node.receiveShadow = true;

        });


        const textureLoader = new THREE.TextureLoader();
        const waterGeometry = new THREE.PlaneGeometry(20, 20);
        const flowMap = textureLoader.load('../static/images/Water_1_M_Flow.jpg');
        water = new THREE.Water(waterGeometry, {
            scale: 1,
            textureWidth: 512,
            textureHeight: 512,
            flowMap: flowMap
        });
        water.position.y = 1;
        water.position.x = -6.4;
        water.rotation.x = Math.PI * - 0.5;
        scene.add(water);
        gltf.scene.position.y = 1;
        scene.add(gltf.scene);
        createWin(labelArr);
        queryOilStatus()

    },
        // 加载过程中的回调函数
        function (xhr) {
            if (loadIndex == 2) {
                setTimeout(() => {
                    AjaxRequest('/valve/list/all?oilCode=&ssStatus=&maStatus=&code=&name='
                        , callback)
                    function callback(result) {

                        var data = result.result;
                        data.forEach(e => {

                            if (e.ssStatus == 1) {//打开

                                changeValveMaterial(e.oilCode + '-' + e.seqNo)

                            }
                            // if (e.maStatus == 0) {//本地
                            //     let selectObject = scene.getObjectByName(e.code)


                            //     var material = new THREE.MeshLambertMaterial({
                            //         color: 0xffff9a ,
                            //         transparent: selectObject.material.transparent ? false : true,
                            //         opacity: 1
                            //     });
                            //     selectObject.material = material;
                            // }

                        });

                    }
                }, 1000);

            }
            loadIndex++
        },
    );
}



// 悬浮名称
function createWin(labelArr) {

    labelArr.forEach(e => {

        let laberDiv = document.createElement('div');
        // $(laberDiv).click(function () {
        //     console.log(111);

        // })

        let fz = e.name.split('-')[1].slice(0, -3);

        if (
            fz == ""
        ) { fz = 0 }
        if (
            e.name.split('-')[1].slice(0, -3) > 12
        ) { fz = 3 }


        $(laberDiv).css({
            // // 'background': 'url(../../static/img/home/3d/' + e.appid + '.png)',
            // 'background-size': 'contain',
            // 'background-repeat': 'no-repeat',
            'font-weight': '400',
            'color': '#666',
            'display': 'flex',
            'align-items': 'center',
            'font-size': (parseInt(fz) * 1 + 10) / 100 + 'rem'
        })
        $(laberDiv).append(`
            <div class="label-ss animate__animated animate__bounce" id="label-ss-${e.name}"></div>
            <div class="label-ma animate__animated animate__bounce" id="label-ma-${e.name}"></div>
            <span id="label-${e.name}">${e.name}</span>
            `)
        let pointLabel = new THREE.CSS2DObject(laberDiv)

        pointLabel.position.set(e.x, e.y, e.z);
        scene.add(pointLabel);
    });



}





// 对象点击事件

var selObjColor = null, selectObject;
function onMouseClick(event) {


    var intersects = getIntersects(event);

    if (selectObject) {
        if (selectObject.material.color) {
            selectObject.material.color.set(selObjColor)
            selectObject.material.opacity = 1
        }

    }


    // 获取选中最近的 Mesh 对象
    if (intersects.length !== 0 && intersects[0].object instanceof THREE.Mesh) {
        selectObject = intersects[0].object;



        if (selectObject.name.indexOf("T-") > -1) {

            selectObject = scene.getObjectByName(selectObject.name.split('-')[0] + '-' + selectObject.name.split('-')[1] + '-0').children[0];


        }


        if (selectObject.parent.name.indexOf("T-") > -1) {

            if (selectObject.material.color) selObjColor = '#' + selectObject.material.color.getHexString()
            changeMaterial(selectObject);
            queryOilValve(selectObject.parent.name)

        } else {
            $('.map-window').hide();
        }
    }


}
$(".close-map-window").click(function () { $('.map-window').hide(); })



// 射线
function getIntersects(event) {
    event.preventDefault();

    var raycaster = new THREE.Raycaster();
    var mouse = new THREE.Vector2();

    mouse.x = (event.offsetX / $('#model-con').width()) * 2 - 1;
    mouse.y = -(event.offsetY / $('#model-con').height()) * 2 + 1;

    raycaster.setFromCamera(mouse, camera);

    var intersects = raycaster.intersectObjects(scene.children, true);

    return intersects;
}



// 改变对象材质属性
function changeMaterial(object) {

    var material = new THREE.MeshLambertMaterial({
        color: 0x31fdba,
        transparent: object.material.transparent ? false : true,
        opacity: 0.6
    });
    object.material = material;

}

changeValveMaterial = (name) => {
    let selectObject = scene.getObjectByName(name)


    var material = new THREE.MeshLambertMaterial({
        color: 0xf2453d,
        transparent: selectObject.material.transparent ? false : true,
        opacity: 1
    });
    selectObject.material = material;
}


//当阀门状态改变时，油罐顶部分区颜色变化
changeOilColor = (msg) => {

    // ma 本地远程  0是本地 1是远程
    // ss 打开关闭  0是关闭 1是打开

    if (msg.dataType == 1) {// 1 开关 
        var name = msg.oilCode + '-' + msg.seqNo

        if (msg.valveStatus == 1) {
            changeValveMaterial(name)

        } else {
            let selectObject = scene.getObjectByName(name)
            if (selectObject.material.color) {
                selectObject.material.color.set(selObjColor)
                selectObject.material.opacity = 1
            }

        }
    }
    //  else if (msg.dataType == 2) {//4 本地丨远程

    //     if (msg.valveStatus == 0) {
    //         changeValveMaterial(name)

    //     } else {
    //         let selectObject = scene.getObjectByName(name)
    //         if (selectObject.material.color) {
    //             selectObject.material.color.set(selObjColor)
    //             selectObject.material.opacity = 1
    //         }

    //     }
    // }


}



var sky, sunSphere;
function initSky() {

    // Add Sky
    sky = new THREE.Sky();
    sky.scale.setScalar(450000);
    scene.add(sky);

    // Add Sun Helper
    sunSphere = new THREE.Mesh(
        new THREE.SphereBufferGeometry(20000, 16, 8),
        new THREE.MeshBasicMaterial({ color: 0x7F6D4D })
    );
    sunSphere.position.y = - 70000;
    // sunSphere.visible = false;
    scene.add(sunSphere);

    /// GUI

    if (!getTimeState()) {
        var effectController = {
            turbidity: 20,
            rayleigh: 4,
            mieCoefficient: 0.001,
            mieDirectionalG: 0.8,
            luminance: 1,
            inclination: 0.49, // elevation / inclination
            azimuth: 0.25, // Facing front,
            sun: ! true
        };
    } else {
        var effectController = {
            turbidity: 10,
            rayleigh: 0.2,
            mieCoefficient: 0.001,
            mieDirectionalG: 0.5,
            luminance: 0.3,
            inclination: 0.48, // elevation / inclination
            azimuth: 0.2, // Facing front,
            sun: ! true
        };
    }


    var distance = 400000;

    var uniforms = sky.material.uniforms;
    uniforms.turbidity.value = effectController.turbidity;
    uniforms.rayleigh.value = effectController.rayleigh;
    uniforms.luminance.value = effectController.luminance;
    uniforms.mieCoefficient.value = effectController.mieCoefficient;
    uniforms.mieDirectionalG.value = effectController.mieDirectionalG;

    var theta = Math.PI * (effectController.inclination - 0.5);
    var phi = 2 * Math.PI * (effectController.azimuth - 0.5);

    sunSphere.position.x = distance * Math.cos(phi);
    sunSphere.position.y = distance * Math.sin(phi) * Math.sin(theta);
    sunSphere.position.z = distance * Math.sin(phi) * Math.cos(theta);

    sunSphere.visible = effectController.sun;

    uniforms.sunPosition.value.copy(sunSphere.position);

    renderer.render(scene, camera);

}
function getTimeState() {
    // 获取当前时间
    let timeNow = new Date();
    // 获取当前小时
    let hours = timeNow.getHours();
    // 设置默认文字
    let state = ``;
    // 判断当前时间段
    if (hours >= 7 && hours <= 18) {
        state = true;
    } else {
        state = false;
    }
    return state;
}

/* 窗口变动触发 */
function onWindowResize() {

    camera.aspect = $('#model-con').width() / $('#model-con').height();
    camera.updateProjectionMatrix();
    renderer.setSize($('#model-con').width(), $('#model-con').height());

}

let clock = new THREE.Clock();

/* 数据更新 */
function update() {


    controls.update(clock.getDelta());

}
/* 初始化 */
function init() {

    initScene();
    initCamera();
    initRender();
    initLight();
    initControls();
    initContent();
    initSky()




    /* 监听事件 */
    window.addEventListener('resize', onWindowResize, false);

    document.getElementById("model-con").addEventListener('click', onMouseClick, false);


}

/* 循环渲染 */
function animate() {

    requestAnimationFrame(animate);
    labelRenderer.render(scene, camera);//渲染

    renderer.render(scene, camera);
    update();

}
